<template>
	<div>
		<!-- 遮罩层 -->
		<div v-if="show" class="user-info-mask" @click="close"></div>

		<!-- 用户信息卡片 -->
		<div v-if="show" class="user-info-card" :style="{ left: pos.x + 'px', top: pos.y + 'px' }" @click.stop>
			<!-- 背景装饰 -->
			<div class="card-backdrop" :style="{ backgroundImage: `url(${user.headImage || user.headImageThumb})` }">
			</div>

			<!-- 卡片内容 -->
			<div class="card-content">
				<!-- 用户头像和基本信息 -->
				<div class="user-header">
					<div class="avatar-container">
						<head-image :name="user.nickName" :url="user.headImageThumb" :size="80" :online="user.online"
							@click.native="showFullImage()" radius="50%" class="user-avatar">
						</head-image>
						<div class="online-badge" :class="{ 'online': user.online }">
							<i :class="user.online ? 'fas fa-circle' : 'fas fa-circle'"></i>
						</div>
					</div>
					<div class="user-basic-info">
						<div class="name-row">
							<h3 class="nick-name">{{ user.nickName }}</h3>
							<div class="gender-badge" v-if="user.sex !== null && user.sex !== undefined">
								<i v-if="user.sex === 1" class="fas fa-mars gender-icon male" title="男"></i>
								<i v-else-if="user.sex === 0" class="fas fa-venus gender-icon female" title="女"></i>
							</div>
						</div>
						<div class="username-row">
							<i class="fas fa-at username-icon"></i>
							<span class="username">{{ user.userName }}</span>
						</div>
						<div class="status-row">
							<span class="online-status" :class="{ 'online': user.online }">
								<i :class="user.online ? 'fas fa-circle' : 'fas fa-circle'"></i>
								{{ user.online ? '在线' : '离线' }}
							</span>
						</div>
					</div>
				</div>

				<!-- 个性签名 -->
				<div class="signature-section">
					<div class="section-title">
						<i class="fas fa-quote-left"></i>
						<span>个性签名</span>
					</div>
					<p class="signature-text">{{ user.signature || '这个人很神秘，什么都没有留下...' }}</p>
				</div>

				<!-- 博客统计信息 -->
				<div class="blog-stats" v-if="blogStats">
					<div class="section-title">
						<i class="fas fa-chart-bar"></i>
						<span>博客数据</span>
					</div>
					<div class="stats-grid">
						<div class="stat-item">
							<div class="stat-value">{{ blogStats.articleCount || 0 }}</div>
							<div class="stat-label">
								<i class="fas fa-file-alt"></i>
								文章
							</div>
						</div>
						<div class="stat-item">
							<div class="stat-value">{{ formatNumber(blogStats.totalViews) || 0 }}</div>
							<div class="stat-label">
								<i class="fas fa-eye"></i>
								阅读
							</div>
						</div>
						<div class="stat-item">
							<div class="stat-value">{{ formatNumber(blogStats.totalLikes) || 0 }}</div>
							<div class="stat-label">
								<i class="fas fa-heart"></i>
								获赞
							</div>
						</div>
					</div>
				</div>

				<!-- 操作按钮 -->
				<div class="action-buttons">
					<el-button v-if="isFriend" type="primary" @click="onSendMessage()" class="action-btn primary-btn">
						<i class="fas fa-comment"></i>
						发消息
					</el-button>
					<el-button v-else type="primary" @click="onAddFriend()" class="action-btn primary-btn">
						<i class="fas fa-user-plus"></i>
						加为好友
					</el-button>
					<el-button @click="viewProfile()" class="action-btn secondary-btn">
						<i class="fas fa-user"></i>
						查看主页
					</el-button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import HeadImage from './HeadImage.vue'
import { addFriendApi } from '@/api/imFriend.js'
import { getProfileCard } from '@/api/profile'

export default {
	name: "userInfo",
	components: {
		HeadImage
	},
	data() {
		return {
			show: false,
			user: {},
			blogStats: null,
			pos: {
				x: 0,
				y: 0
			}
		}
	},
	methods: {
		async open(user, pos) {
			this.show = true;
			this.user = user;

			// 计算弹窗位置，智能定位优化用户体验
			this.calculateOptimalPosition(pos);

			// 添加键盘事件监听
			this.addKeyboardListener();

			// 获取用户博客统计数据
			await this.loadBlogStats();
		},

		calculateOptimalPosition(clickPos) {
			const w = document.documentElement.clientWidth;
			const h = document.documentElement.clientHeight;
			const scrollY = window.scrollY || document.documentElement.scrollTop;

			// 响应式卡片尺寸配置
			const isMobile = w <= 768;
			const cardWidth = isMobile ? Math.min(360, w - 32) : 380;
			const cardHeight = isMobile ? Math.min(400, h * 0.8) : 450;
			const margin = isMobile ? 16 : 20;
			const offsetX = isMobile ? 8 : 12;
			const offsetY = isMobile ? 8 : 12;

			// 可视区域计算（考虑滚动）
			const viewportTop = scrollY;
			const viewportBottom = scrollY + h;
			const safeAreaTop = viewportTop + margin;
			const safeAreaBottom = viewportBottom - margin - 100; // 预留底部空间

			// 智能X坐标计算
			let targetX = clickPos.x + offsetX;

			// 如果右侧空间不足，显示在左侧
			if (targetX + cardWidth > w - margin) {
				targetX = clickPos.x - cardWidth - offsetX;
				// 如果左侧也不够，居中显示
				if (targetX < margin) {
					targetX = Math.max(margin, (w - cardWidth) / 2);
				}
			}

			// 智能Y坐标计算
			let targetY = clickPos.y + offsetY;

			// 检查底部空间
			if (targetY + cardHeight > safeAreaBottom) {
				// 尝试显示在点击位置上方
				targetY = clickPos.y - cardHeight - offsetY;

				// 如果上方空间也不足，智能调整
				if (targetY < safeAreaTop) {
					// 计算最佳垂直位置
					const availableHeight = safeAreaBottom - safeAreaTop;
					if (availableHeight >= cardHeight) {
						// 垂直居中在可视区域
						targetY = safeAreaTop + (availableHeight - cardHeight) / 2;
					} else {
						// 贴顶显示，让内容可滚动
						targetY = safeAreaTop;
					}
				}
			}

			// 确保不超出边界
			this.pos.x = Math.max(margin, Math.min(targetX, w - cardWidth - margin));
			this.pos.y = Math.max(safeAreaTop, Math.min(targetY, safeAreaBottom - cardHeight));
		},
		close() {
			// 移除键盘事件监听
			this.removeKeyboardListener();

			// 添加消失动画
			const card = document.querySelector('.user-info-card');
			if (card) {
				card.classList.add('fade-out');
				setTimeout(() => {
					this.show = false;
					this.blogStats = null;
				}, 200); // 与动画时长匹配
			} else {
				this.show = false;
				this.blogStats = null;
			}
		},

		addKeyboardListener() {
			document.addEventListener('keydown', this.handleKeydown);
		},

		removeKeyboardListener() {
			document.removeEventListener('keydown', this.handleKeydown);
		},

		handleKeydown(event) {
			if (event.key === 'Escape' && this.show) {
				this.close();
			}
		},
		async loadBlogStats() {
			try {
				const response = await getProfileCard(this.user.id);
				this.blogStats = response.data;
			} catch (error) {
				console.warn('获取用户博客数据失败:', error);
				// 不显示错误信息，静默失败
			}
		},
		/**
		 * 点击发消息按钮，跳转到聊天界面
		 * 注意：这里不更新会话时间，保持最近聊天记录的时间
		 */
		onSendMessage() {
			let user = this.user;
			let chat = {
				type: 'PRIVATE',
				targetId: user.id,
				showName: user.nickName,
				headImage: user.headImage || user.headImageThumb
			};
			if (this.isFriend) {
				chat.isDnd = this.friendInfo.isDnd;
			}
			// 第二个参数为false，表示不更新会话时间
			this.chatStore.openChat(chat, false);
			this.chatStore.setActiveChat(0);
			if (this.$route.path != "/im/chat") {
				this.$router.push("/im/chat");
			}
			this.show = false;
		},
		onAddFriend() {
			addFriendApi(this.user.id).then(() => {
				this.$message.success("添加成功，对方已成为您的好友");
				let friend = {
					id: this.user.id,
					nickName: this.user.nickName,
					headImage: this.user.headImageThumb,
					online: this.user.online,
					deleted: false
				}
				this.friendStore.addFriend(friend);
			}).catch((error) => {
				this.$message.error("添加好友失败：" + (error.message || "未知错误"));
			})
		},
		viewProfile() {
			// 跳转到用户主页
			const routeData = this.$router.resolve({
				path: `/user/${this.user.id}`
			});
			window.open(routeData.href, '_blank');
			this.show = false;
		},
		showFullImage() {
			if (this.user.headImage || this.user.headImageThumb) {
				this.$eventBus.$emit("openFullImage", this.user.headImage || this.user.headImageThumb);
			}
		},
		formatNumber(num) {
			if (!num) return '0';
			if (num >= 10000) {
				return (num / 10000).toFixed(1) + 'w';
			} else if (num >= 1000) {
				return (num / 1000).toFixed(1) + 'k';
			}
			return num.toString();
		}
	},
	computed: {
		isFriend() {
			return this.friendStore.isFriend(this.user.id);
		},
		friendInfo() {
			return this.friendStore.findFriend(this.user.id);
		}
	},
	beforeDestroy() {
		// 组件销毁时清理事件监听
		this.removeKeyboardListener();
	}
}
</script>

<style lang="scss" scoped>
@use "@/styles/variables.scss" as *;

// 遮罩层
.user-info-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: transparent;
	z-index: 99998;
}

.user-info-card {
	position: fixed;
	width: 380px;
	max-height: min(450px, 80vh); // 更合理的高度限制
	background: var(--im-bg-primary);
	border-radius: 12px; // 更圆润的边角
	box-shadow:
		0 8px 32px rgba(0, 0, 0, 0.12),
		0 4px 16px rgba(0, 0, 0, 0.08),
		0 0 0 1px rgba(255, 255, 255, 0.05);
	overflow: hidden;
	z-index: 99999;
	border: 1px solid rgba(255, 255, 255, 0.1);
	animation: cardAppear 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
	backdrop-filter: blur(20px) saturate(180%);
	transform-origin: top left;
}

@keyframes fadeInUp {
	from {
		opacity: 0;
		transform: translateY(20px);
	}

	to {
		opacity: 1;
		transform: translateY(0);
	}
}

// 背景装饰
.card-backdrop {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	height: 120px;
	background-size: cover;
	background-position: center;
	background-repeat: no-repeat;
	filter: blur(20px) brightness(0.3);
	opacity: 0.6;
	z-index: 1;
}

// 卡片内容
.card-content {
	position: relative;
	z-index: 2;
	padding: 20px;
	max-height: min(430px, calc(80vh - 40px)); // 更合理的高度限制
	overflow-y: auto;
	overflow-x: hidden;
	scroll-behavior: smooth;

	// 优化的滚动条样式
	&::-webkit-scrollbar {
		width: 4px;
	}

	&::-webkit-scrollbar-track {
		background: transparent;
	}

	&::-webkit-scrollbar-thumb {
		background: rgba(255, 255, 255, 0.2);
		border-radius: 2px;
		transition: background 0.2s ease;

		&:hover {
			background: rgba(255, 255, 255, 0.3);
		}
	}

	// 滚动渐变遮罩效果
	&::before {
		content: '';
		position: sticky;
		top: 0;
		left: 0;
		right: 0;
		height: 20px;
		background: linear-gradient(to bottom, var(--im-bg-primary), transparent);
		z-index: 1;
		pointer-events: none;
	}

	&::after {
		content: '';
		position: sticky;
		bottom: 0;
		left: 0;
		right: 0;
		height: 20px;
		background: linear-gradient(to top, var(--im-bg-primary), transparent);
		z-index: 1;
		pointer-events: none;
	}
}

// 用户头部信息
.user-header {
	display: flex;
	align-items: flex-start;
	margin-bottom: var(--im-spacing-lg);
	position: relative;
}

// 头像容器
.avatar-container {
	position: relative;
	margin-right: var(--im-spacing-base);
	flex-shrink: 0;

	.user-avatar {
		border: 3px solid var(--im-bg-primary);
		box-shadow: var(--im-box-shadow-base);
		cursor: pointer;
		transition: all var(--im-transition-base);

		&:hover {
			transform: scale(1.05);
			box-shadow: var(--im-box-shadow-hover);
		}
	}

	.online-badge {
		position: absolute;
		bottom: 8px;
		right: 8px;
		width: 16px;
		height: 16px;
		border-radius: 50%;
		background: var(--im-text-color-disabled);
		border: 2px solid var(--im-bg-primary);
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 8px;
		color: white;

		&.online {
			background: var(--im-color-success);
		}
	}
}

// 用户基本信息
.user-basic-info {
	flex: 1;
	min-width: 0;

	.name-row {
		display: flex;
		align-items: center;
		margin-bottom: var(--im-spacing-xs);

		.nick-name {
			font-size: var(--im-font-size-xl);
			font-weight: var(--im-font-weight-bold);
			color: var(--im-text-color-primary);
			margin: 0;
			margin-right: var(--im-spacing-sm);
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		.gender-badge {
			.gender-icon {
				font-size: var(--im-font-size-base);

				&.male {
					color: var(--im-color-primary);
				}

				&.female {
					color: #ff69b4;
				}
			}
		}
	}

	.username-row {
		display: flex;
		align-items: center;
		margin-bottom: var(--im-spacing-xs);
		font-size: var(--im-font-size-sm);
		color: var(--im-text-color-secondary);

		.username-icon {
			margin-right: var(--im-spacing-xs);
			color: var(--im-text-color-placeholder);
		}

		.username {
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}

	.status-row {
		.online-status {
			display: inline-flex;
			align-items: center;
			font-size: var(--im-font-size-xs);
			color: var(--im-text-color-disabled);
			background: var(--im-bg-secondary);
			padding: 2px 8px;
			border-radius: var(--im-border-radius-round);

			&.online {
				color: var(--im-color-success);
				background: var(--im-color-success-light-9);
			}

			i {
				font-size: 6px;
				margin-right: 4px;
			}
		}
	}
}

// 区块标题
.section-title {
	display: flex;
	align-items: center;
	font-size: var(--im-font-size-sm);
	font-weight: var(--im-font-weight-semibold);
	color: var(--im-text-color-primary);
	margin-bottom: var(--im-spacing-sm);

	i {
		margin-right: var(--im-spacing-xs);
		color: var(--im-color-primary);
	}
}

// 个性签名区域
.signature-section {
	margin-bottom: var(--im-spacing-lg);
	padding: var(--im-spacing-base);
	background: var(--im-bg-secondary);
	border-radius: var(--im-border-radius-base);
	border-left: 3px solid var(--im-color-primary);

	.signature-text {
		font-size: var(--im-font-size-sm);
		color: var(--im-text-color-secondary);
		line-height: 1.5;
		margin: 0;
		font-style: italic;
	}
}

// 博客统计区域
.blog-stats {
	margin-bottom: var(--im-spacing-lg);

	.stats-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: var(--im-spacing-sm);
	}

	.stat-item {
		text-align: center;
		padding: var(--im-spacing-base);
		background: var(--im-bg-secondary);
		border-radius: var(--im-border-radius-base);
		transition: all var(--im-transition-base);

		&:hover {
			background: var(--im-bg-hover);
			transform: translateY(-2px);
			box-shadow: var(--im-box-shadow-hover);
		}

		.stat-value {
			font-size: var(--im-font-size-lg);
			font-weight: var(--im-font-weight-bold);
			color: var(--im-color-primary);
			margin-bottom: 2px;
		}

		.stat-label {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: var(--im-font-size-xs);
			color: var(--im-text-color-secondary);

			i {
				margin-right: 2px;
			}
		}
	}
}

// 操作按钮
.action-buttons {
	display: flex;
	gap: var(--im-spacing-sm);

	.action-btn {
		flex: 1;
		border-radius: var(--im-border-radius-base);
		font-size: var(--im-font-size-sm);
		padding: var(--im-spacing-sm) var(--im-spacing-base);
		transition: all var(--im-transition-base);

		i {
			margin-right: var(--im-spacing-xs);
		}

		&:hover {
			transform: translateY(-1px);
			box-shadow: var(--im-box-shadow-hover);
		}
	}

	.primary-btn {
		background: var(--im-color-primary);
		border-color: var(--im-color-primary);
		color: white;

		&:hover {
			background: var(--im-color-primary-dark-1);
			border-color: var(--im-color-primary-dark-1);
		}
	}

	.secondary-btn {
		background: var(--im-bg-secondary);
		border-color: var(--im-border-color);
		color: var(--im-text-color-secondary);

		&:hover {
			background: var(--im-bg-hover);
			border-color: var(--im-text-color-secondary);
			color: var(--im-text-color-primary);
		}
	}
}

// 动画效果
@keyframes cardAppear {
	0% {
		opacity: 0;
		transform: translateY(8px) scale(0.96);
		filter: blur(4px);
	}

	60% {
		opacity: 0.8;
		transform: translateY(-2px) scale(1.01);
		filter: blur(0px);
	}

	100% {
		opacity: 1;
		transform: translateY(0) scale(1);
		filter: blur(0px);
	}
}

// 卡片消失动画
.user-info-card.fade-out {
	animation: cardDisappear 0.2s ease-in forwards;
}

@keyframes cardDisappear {
	from {
		opacity: 1;
		transform: translateY(0) scale(1);
	}

	to {
		opacity: 0;
		transform: translateY(-8px) scale(0.95);
	}
}

// 响应式优化
@media (max-width: 768px) {
	.user-info-card {
		width: calc(100vw - 32px) !important;
		max-width: 360px;
		max-height: 80vh;

		.card-content {
			padding: 16px;
			max-height: calc(80vh - 32px);
		}

		.user-header {
			.user-avatar {
				width: 60px;
				height: 60px;
			}

			.user-details {
				.user-name {
					font-size: 18px;
				}
			}
		}

		.stats-grid {
			grid-template-columns: repeat(2, 1fr);
			gap: 12px;

			.stat-item {
				padding: 12px;
			}
		}

		.action-buttons {
			flex-direction: column;
			gap: 8px;

			.action-btn {
				padding: 12px 16px;
				font-size: 14px;
			}
		}
	}
}

// 小屏幕优化
@media (max-width: 480px) {
	.user-info-card {
		.stats-grid {
			grid-template-columns: 1fr;
		}
	}
}
</style>